package org.liuyuantao.thread.concurrent;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * Phaser提供了比CountDownLatch、CyclicBarrier更加强大、灵活的功能，从某种程度上来说，Phaser可以替换他们
 */
public class PhaserTest {
    public static void main(String[] args) {
        Phaser phaser = new Phaser(5);

        for (int i = 0; i < 5; i++) {
            Task_01 task_01 = new Task_01(phaser);
            Thread thread = new Thread(task_01, "PhaseTest_" + i);
            thread.start();
        }
        Phaser phaser2 = new Phaser(1);        //相当于CountDownLatch(1)

        //五个子任务
        for (int i = 0; i < 3; i++) {
            Task_02 task2 = new Task_02(phaser);
            Thread thread = new Thread(task2, "PhaseTest_" + i);
            thread.start();
        }

        try {
            //等待3秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //类似CountDownLatch的countDown
        phaser2.arrive();
    }

    static class Task_01 implements Runnable {
        private final Phaser phaser;

        public Task_01(Phaser phaser) {
            this.phaser = phaser;
        }

        @Override
        public void run() {
            try {
                TimeUnit.MILLISECONDS.sleep(new Random().nextInt(5000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "执行任务完成，等待其他任务执行......");
            //等待其他任务执行完成
            phaser.arriveAndAwaitAdvance();
            try {
                TimeUnit.MILLISECONDS.sleep(new Random().nextInt(3000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "继续执行任务...");
        }
    }

    static class Task_02 implements Runnable {
        private final Phaser phaser;

        Task_02(Phaser phaser) {
            this.phaser = phaser;
        }

        @Override
        public void run() {
            //类似CountDownLatch的await
            phaser.awaitAdvance(phaser.getPhase());        //countDownLatch.await()
            System.out.println(Thread.currentThread().getName() + "执行任务...");
        }
    }
}